<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Upload extends CI_Controller {
    
    // ------------------------------------------------------------------------
    
    /**
     * Array of allowed file extensions to upload.
     * 
     * @var array
     */
    protected $_extensions = array('png', 'jpeg', 'jpg', 'gif', 'bmp'); // Acceptable file extensions
    
    /**
     * Directory files get uploaded to.
     * 
     * @var string
     */
    protected $_directory = '/uploads/images/full';
    
    /**
     * Max Upload Size limit in bytes.
     * 
     * @var integer
     */
    protected $_size_limit = 10485760;
    
    /**
     * Place holder for error message.
     * 
     * @var string
     */
    public $error;
    
    // ------------------------------------------------------------------------
    
    public function index() {
        redirect('/tai-khoan');
    }
    public function __construct() {
        parent::__construct();
        
        // Everything that happens here gets told in JSON format!
        $this->output->set_content_type('application/json');
        
        if ($this->input->get_post('sizeLimit')) {
            //logit('Ajax_uploader - Setting sizeLimit via script to - ' . $this->input->post('sizeLimit'));
            $this->_size_limit = (int) $this->input->post('sizeLimit');
        }
        
        // Check directory exists, is writable, etc.
        $this->_directory = $this->check_directory();
        
        $this->_directory = rtrim($this->_directory, '/') . '/';
        
        // Check the server post/upload size against the size_limit.
        //$this->check_server_settings();
        
        $this->load->helper('security');
        // $this->load->library('security');
        //logit('Ajax_uploader class inited');
        
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * The main method, handles uploading files via Valums Ajax File script.
     * 
     * @return void
     */
    public function upload_files($type = false) {
		
        $json = array(
            'error' => 'Something really really bad happened, and well I donnu what :(.'
        );
        
        $file = NULL;
        if ($this->input->get('qqfile')) {
            $file = $this->input->get('qqfile');
        } elseif (isset($_FILES) && array_key_exists('qqfile', $_FILES)) {
            $file = $_FILES['qqfile']['tmp_name'];
        }
        
      if (isset($file) && $file !== NULL){
			//$this->security->xss_clean($file)
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            
            if (in_array($ext, $this->_extensions)) {
                $directory = $this->_directory;
                
                $this->load->helper('url');
                
                //$filename = str_replace('.' . $ext, '', $file);
                //$filename = strtolower(url_title($filename));					 
                //$filename .= '.' . $ext;
					 $filename = md5(uniqid(mt_rand())).'.'.$ext;
                
                if ($this->input->get('qqfile')) {
                    $input = fopen('php://input', 'r');
                    $temp  = tmpfile();
                    if ($temp === FALSE) {
                        $this->error_report('Failed to create upload file.');
                    }
                    
                    $real_size = stream_copy_to_stream($input, $temp);
                    fclose($input);
                    /*
                    if ($real_size != $this->get_size())
                    {
                    $this->error_report('File did not completely upload. Try again.');						
                    }
                    */
                    
                    $target = fopen($directory . $filename, 'w');
                    fseek($temp, 0, SEEK_SET);
                    stream_copy_to_stream($temp, $target);
                    fclose($target);
               } elseif ($_FILES['qqfile']) {
                    move_uploaded_file($_FILES['qqfile']['tmp_name'], $directory . $filename . '.' . $ext);
               }
					$album_id = '';
					switch($type){
						case 'album':
							//save in database							
							//save to album
							$this->load->model('album_m', 'album');
							$album_id = $this->album->create_album($filename);
						break;
						case 'avatar':
							//update avatar of current user
							$this->load->model('album_m', 'album');
							$album_id = $this->album->update_avatar($filename);
						break;
					}
					//save to media
					$this->load->model('media_m', 'media');
					$tmp = getimagesize($directory . $filename);
					$data['file_name'] = $filename;
					$data['width']	= 	$tmp[0];
					$data['height']= 	$tmp[1];
					$data['type']	=	$tmp['mime'];
					$data['size']	= 	filesize($directory . $filename);
					$data['path']	=	'uploads/images/full/' . $filename;
					date_default_timezone_set('Asia/Bangkok');		
					$data['created']= date('Y-m-d H:i:s');
					$media_id = $this->media->save_media($data);
					//
               $json = array(
                  'success' 	=> 'true',
                  'filename' 	=> $filename,
						'albumId'	=>	$album_id,
						'media_id'	=> $media_id,
						'url'			=>	base_url($data['path'])
               );
            } else {
                $this->error_report('File type not supported.');
            }
        }
        
        $this->output->set_output(json_encode($json));
    }
    
    
    // ------------------------------------------------------------------------
    // PRIVATE METHODS!
    // ------------------------------------------------------------------------
    
    // ------------------------------------------------------------------------
    
    /**
     * Gets File Size by Content Length Server Setting. Isn't Ajax File Uploading Fun!
     * 
     * @return int
     */
    private function get_size() {
        if ($this->input->server('CONTENT_LENGTH')) {
            return (int) $this->input->server('CONTENT_LENGTH');
        } else {
            //logit('Ajax_Uploader Failed - Getting content length is not supported.', 'error');
            throw new Exception('Getting content length is not supported.');
        }
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Handles Error reports, logs them, and sends a json response back to the script.
     *
     * @access private
     * 
     * @param  string $message Error message to display
     * 
     * @return void
     */
    private function error_report($message = '') {
        $this->error = $message;
        //logit('Ajax_Uploader failed - '.$this->error, 'error');
        $this->output->set_output(json_encode(array(
            'error',
            $message
        )));
        die;
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Checks Server Max Upload and Post Sizes against the Size limit to verify your not nuts.
     *
     * @access private
     * 
     * @return void
     */
    private function check_server_settings() {
        $post_size   = $this->to_bytes(ini_get('post_max_size'));
        $upload_size = $this->to_bytes(ini_get('upload_max_filesize'));
        
        if ($post_size < $this->_size_limit || $upload_size < $this->_size_limit) {
            $size = max(1, $this->_size_limit / 1024 / 1024) . 'M';
            $this->error_report('Increase post_max_size and upload_max_filesize to ' . $size);
            return FALSE;
        }
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Converts Filesize into Kilobytes.
     *
     * @access private
     * 
     * @param  string $str Filesize to be converted
     * 
     * @return int
     */
    private function to_bytes($str) {
        $val  = trim($str);
        $last = strtolower($str[strlen($str) - 1]);
        switch ($last) {
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }
        return $val;
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Checks upload directory to make sure it exists, if not trys to create one or fails with status message.
     *
     * @access private
     * 
     * @return string
     */
    private function check_directory() {
        $directory = realpath(FCPATH . $this->_directory);
        
        if (!is_dir($directory)) {
            $status = mkdir($directory, DIR_WRITE_MODE);
            if (!$status) {
                $this->error_report('Directory does not exist and could not be created.');
            }
        }
        
        if (!is_writable($directory)) {
            $status = chmod($directory, DIR_WRITE_MODE);
            if (!$status) {
                $this->error_report('Server error. Upload directory isn\'t writable.');
            }
        }
        
        return $directory;
    }
    
    
}

/* End of file ajax_uploader.php */
/* Location: ./application/controllers/ajax_uploader.php */